import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { authService } from '../services/auth';
import { Models } from 'appwrite';

interface AuthContextType {
  user: Models.User<Models.Preferences> | null;
  loading: boolean;
  login: (email: string, password: string) => Promise<boolean>;
  register: (email: string, password: string, name: string) => Promise<boolean>;
  oauthLogin: (provider: 'google' | 'github') => Promise<void>;
  logout: () => Promise<void>;
  isAuthenticated: boolean;
  isAdmin: boolean;
  getUserAvatarUrl: () => string;
  checkAuth: () => Promise<void>;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export const AuthProvider = ({ children }: { children: ReactNode }) => {
  const [user, setUser] = useState<Models.User<Models.Preferences> | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    checkAuth();
  }, []);

  const checkAuth = async () => {
    try {
      const result = await authService.getCurrentUser();
      if (result.success && result.user) {
        setUser(result.user);
      }
    } catch (error) {
      console.error('Auth check failed:', error);
    } finally {
      setLoading(false);
    }
  };

  const login = async (email: string, password: string): Promise<boolean> => {
    try {
      const result = await authService.emailLogin(email, password);
      if (result.success) {
        const userResult = await authService.getCurrentUser();
        if (userResult.success && userResult.user) {
          setUser(userResult.user);
          return true;
        }
      }
      return false;
    } catch (error) {
      console.error('Login failed:', error);
      return false;
    }
  };

  const register = async (email: string, password: string, name: string): Promise<boolean> => {
    try {
      const result = await authService.emailRegister(email, password, name);
      if (result.success) {
        const userResult = await authService.getCurrentUser();
        if (userResult.success && userResult.user) {
          setUser(userResult.user);
          return true;
        }
      }
      return false;
    } catch (error) {
      console.error('Registration failed:', error);
      return false;
    }
  };

  const oauthLogin = async (provider: 'google' | 'github'): Promise<void> => {
    await authService.oauthLogin(provider);
  };

  const logout = async (): Promise<void> => {
    try {
      console.log('AuthContext: Starting logout process...');
      await authService.logout();
      console.log('AuthContext: Logout successful, clearing user state');
      setUser(null);
    } catch (error) {
      console.error('AuthContext: Logout failed:', error);
      // Even if logout fails on server, clear local state
      setUser(null);
    }
  };

  // Check if user has admin label
  const isAdmin = user?.labels?.includes('admin') || false;

  // Get user avatar URL using Appwrite Avatars service
  const getUserAvatarUrl = (): string => {
    if (!user) return '';
    return authService.getUserAvatarUrl(user.name || user.email);
  };

  const value: AuthContextType = {
    user,
    loading,
    login,
    register,
    oauthLogin,
    logout,
    isAuthenticated: !!user,
    isAdmin,
    getUserAvatarUrl,
    checkAuth, // Expose checkAuth so components can refresh user state
  };

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};
